package cn.xej.demo1;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author alicat.xu
 * @Date 2021/10/26 11:15 上午
 */
@Slf4j
public class Server {

    /**
     * 使用nio来理解阻塞模式，单线程
     */
    @Test
    public void blockModel() throws IOException{
        ByteBuffer buffer = ByteBuffer.allocate(16);
        //1、创建服务器
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //2、服务器绑定监听的端口号
        ServerSocketChannel ssc = socketChannel.bind(new InetSocketAddress(8080));

        List<SocketChannel> channels = new ArrayList<>();

        while (true){
            log.debug("connecting....");
            //建立与客户端的链接，SocketChannel用来与客户端之间通信
            SocketChannel sc = ssc.accept(); //阻塞方法，线程停止运行
            log.debug("connected...{} ",sc);
            channels.add(sc);

            for (SocketChannel channel : channels) {
                log.debug("before read {} ",channel);
                //从套接字通道(信道)读取数据写入到buffer中
                channel.read(buffer); //阻塞方法，线程停止运行
                //buffer从写模式转为读模式
                buffer.flip();
                //读取buffer
                debugRead(buffer);
                System.out.println();
                //清空buffer，buffer从读模式转为写模式
                buffer.clear();
                log.debug("after read {} ",channel);
            }
        }
    }

    /**
     * 使用nio来理解非阻塞模式，单线程
     * 缺点：程序会一直循环的遍历，cpu会过高
     */
    @Test
    public void noBlockModel() throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(16);
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        ServerSocketChannel ssc = socketChannel.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false); //作用是使ssc.accept()方法变成非阻塞
        List<SocketChannel> channels = new ArrayList<>();

        while (true){
            SocketChannel sc = ssc.accept();//非阻塞，线程还会继续运行
            if (sc != null){
                log.debug("connected...{} ",sc);
                sc.configureBlocking(false); //作用是使chanel.read(buffer)方法变成非阻塞
                channels.add(sc);
            }
            for (SocketChannel chanel : channels) {
                int i = chanel.read(buffer);//非阻塞，线程还会继续运行
                if (i > 0){
                    buffer.flip();
                    debugRead(buffer);
                    System.out.println();
                    buffer.clear();
                    log.debug("after read {}",chanel);
                }
            }
        }
    }

    private void debugRead(ByteBuffer buffer) {
        while (buffer.hasRemaining()){
            byte b = buffer.get();
            System.out.print((char) b);
        }
    }

    public static void main(String[] args) throws IOException {


    }

}
